<?php
/*
Plugin Name: 七牛云备份
Plugin URI: https://www.beizigen.com/post/wordpress-lightweight-qiniu-cloud-storage-backup-plug-in-backup-qiniu-lite/
Description: 将网站附件、数据库实时备份到七牛云存储。
Version: 1.1.0
Author: 背字根
Author URI: https://www.beizigen.com
*/
require_once('functions.php');

function backup_qiniu_control()
{
	if (isset($_POST['action'])) {
		//保存设置
		if ('保存设置' == $_POST['action']) {
			$data = array(
				'cycle' => sanitize_text_field($_POST['cycle']),
				'bucket_name' => sanitize_text_field($_POST['bucket_name']),
				'access_key' => sanitize_text_field($_POST['access_key']),
				'secret_key' => sanitize_text_field($_POST['secret_key']),
			);

			backup_qiniu_delete_cron();
			if ($data['cycle'] != 'close') {
				wp_schedule_event(time(), $data['cycle'], 'backup_qiniu');
			}
			unset($data['cycle']);
			$data = serialize($data);
			update_option('backup_qiniu', $data);
			echo '<div class="notice is-dismissible updated">设置保存成功！</div>';
		}
		//备份数据
		if ('立即备份' == $_POST['action']) {
			$error = backup_qiniu_mysql();
			if ($error) {
				echo '<div class="notice is-dismissible error">' . $error . '</div>';
			} else {
				echo '<div class="notice is-dismissible updated">备份数据库成功！</div>';
			}
		}
		//初始同步
		if ('initialize' == $_POST['action']) {
			if (function_exists('set_time_limit') && function_exists('ignore_user_abort')) {
				set_time_limit(0);
				ignore_user_abort(true);
				$attachments = backup_qiniu_get_attachment_ids();
				if ($attachments) {
					$Qiniu = new Qiniu();
					$error = $Qiniu->auth();
					if ($error) {
						echo '<div class="notice is-dismissible error">初始化凭证失败：' . $error . '</div>';
					} else {
						$domain = parse_url(get_option('siteurl'));
						$domain = $domain['host'];
						$upload_path = get_option('upload_path');
						$upload_path = $upload_path ? trim($upload_path, '/') : 'wp-content/uploads';
						$upload_path = ABSPATH . $upload_path . '/';

						foreach ($attachments as $attachment) {
							if (wp_attachment_is_image($attachment)) {
								$meta = wp_get_attachment_metadata($attachment);
								$backup_sizes = get_post_meta($attachment, '_wp_attachment_backup_sizes', true);
								if ($backup_sizes) {
									$meta['sizes'] = wp_parse_args($meta['sizes'], $backup_sizes);
								}
								$images = backup_qiniu_images($meta);
								$images = array_unique($images);
								foreach ($images as $image) {
									$save = $domain . '/uploads/' . $image;
									$Qiniu->token($save);
									$upload = $Qiniu->upload($save, $upload_path . $image);
									if ($upload) $error .= $upload . ' - ' . $image . '<br>';
								}
							} else {
								$file = get_attached_file($attachment);
								$path = str_replace($upload_path, '', $file);
								$save = $domain . '/uploads/' . $path;
								$Qiniu->token($save);
								$error = $Qiniu->upload($save, $file);
								if ($error) $error .= ' - ' . $path;
							}
						}
						$mesage = $error ? "上传错误报告：<br><br> $error" : '初始同步已完成，全部附件上传成功。';
						backup_qiniu_mail($mesage);
					}
				} else {
					echo '<div class="notice is-dismissible error">没有找到任何附件。</div>';
				}
			} else {
				echo '<div class="notice is-dismissible error">该功能需要set_time_limit和ignore_user_abort函数支持，请联系主机服务商开启。</div>';
			}
		}
	}
	$options = get_option('backup_qiniu');
	$options = unserialize($options);
	$cycle = wp_get_schedule('backup_qiniu');
	$bucket_name = $access_key = $secret_key = '';
	if ($options) {
		$bucket_name = $options['bucket_name'];
		$access_key = $options['access_key'];
		$secret_key = $options['secret_key'];
	}
?>
	<style type="text/css">
		#wpwrap .notice {
			margin-left: 0;
			margin-top: 15px;
			padding: 1em;
		}

		.mywrap {
			background-color: #fff;
			padding: 5px 20px;
			border-radius: 4px;
			border: 1px solid #ccc;
			margin: 15px 15px 15px 0;
		}

		#initialize {
			background-color: #f5f5f5;
			padding: 10px 15px;
			margin: 30px 0 10px 0;
			border-radius: 4px;
			border: 1px solid #ddd;
			opacity: .6;
		}

		#initialize .button {
			margin-top: 10px;
		}

		@media screen and (max-width: 782px) {
			.mywrap .button-primary {
				min-height: 40px;
			}
		}
	</style>
	<div class="mywrap">
		<h2>七牛云备份</h2>
		<p>上传附件实时备份到七牛云存储，支持定时备份数据库。</p>
		<form method="post" action="<?php echo admin_url('options-general.php?page=backup_qiniu'); ?>">
			<table class="form-table">
				<tbody>
					<tr>
						<th scope="row"><label for="cycle">定时备份</label></th>
						<td>
							<select name="cycle" id="cycle">
								<option value="daily" <?php if ('daily' == $cycle) echo ' selected'; ?>>每天</option>
								<option value="weekly" <?php if ('weekly' == $cycle) echo ' selected'; ?>>每周</option>
								<option value="monthly" <?php if ('monthly' == $cycle) echo ' selected'; ?>>每月</option>
								<option value="close" <?php if (!$cycle) echo ' selected'; ?>>关闭定时</option>
							</select>
							<p class="description">定时备份仅针对数据库，附件是实时同步到云存储的</p>
						</td>
					</tr>
					<tr>
						<th scope="row">
							<label for="bucketname">Bucket Name</label>
						</th>
						<td>
							<input id="bucketname" name="bucket_name" class="regular-text code" type="text" value="<?php echo $options['bucket_name']; ?>" required>
							<p class="description">存储空间名称</p>
						</td>
					</tr>
					<tr>
						<th scope="row">
							<label for="accesskey">Access Key</label>
						</th>
						<td>
							<input id="accesskey" name="access_key" class="regular-text code" type="text" value="<?php echo $options['access_key']; ?>" required>
							<p class="description">密钥<a href="https://portal.qiniu.com/user/key" target="_blank" rel="noopener noreferrer nofollow">登录七牛个人中心</a>获取</p>
						</td>
					</tr>
					<tr>
						<th scope="row">
							<label for="secretkey">Secret Key</label>
						</th>
						<td>
							<input id="secretkey" name="secret_key" class="regular-text code" type="text" value="<?php echo $options['secret_key']; ?>" required>
						</td>
					</tr>
				</tbody>
			</table>
			<p><input class="button-primary" type="submit" name="action" value="保存设置">&nbsp;&nbsp;
				<input class="button" type="submit" name="action" value="立即备份">
			</p>
		</form>
		<form id="initialize" method="post" action="<?php echo admin_url('options-general.php?page=backup_qiniu'); ?>">
			<p>初始同步用于初次安装插件时，将以往上传的附件同步到七牛云存储；</p>
			<p>安装插件之后上传的附件会实时同步到七牛云存储，数据库可以设置定时备份，或在更新文章后点击“立即备份”；</p>
			<p>任务执行完毕会发送邮件到<?php echo get_bloginfo('admin_email'); ?>，关闭网页不影响执行。</p>
			<p>
				<input class="button" type="submit" value="初始同步" onclick="disabled=true; submit();">
				<input type="hidden" name="action" value="initialize">
			</p>
		</form>
	</div>

<?php
}

//添加菜单
function backup_qiniu_menu()
{
	//add_menu_page('七牛云备份', '数据备份', 'administrator', 'backup_qiniu', 'backup_qiniu_control', 'dashicons-cloud', 100);
	add_options_page('七牛云备份', '七牛云备份', 'administrator', 'backup_qiniu', 'backup_qiniu_control');
}
add_action('admin_menu', 'backup_qiniu_menu');
//插件页面设置链接
add_filter('plugin_action_links', function ($links, $file) {
	if ($file == plugin_basename(__FILE__)) {
		array_unshift($links, '<a href="options-general.php?page=backup_qiniu">设置</a>');
	}
	return $links;
}, 10, 2);
?>